<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 使用layout栅格系统 -->
            <el-row
              v-for="(item1,index) in scope.row.children"
              :key="item1.id"
              :gutter="20"
              :class="['borderBottom',index === 0 ? 'borderTop':'']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="6">
                <el-tag closable @close="removeRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="18">
                <!-- 通过for循环嵌套渲染 -->
                <el-row v-for="item2 in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRight(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRight(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="remove(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialog" width="50%" @close="resetRoleForm">
      <!-- 表单主体部分 -->
      <el-form :model="roleForm" :rules="roleFormRules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="rolename">
          <el-input v-model="roleForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescription">
          <el-input v-model="roleForm.roleDescription"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoleQuest">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialog" width="50%" @close="resetEditRoleForm">
      <el-form
        :model="editroleForm"
        :rules="editRoleFormRules"
        ref="editroleForm"
        label-width="100px"
      >
        <!-- **el-form-item绑定的prop必须和该item下的表单元素绑定的v-model值的名称一致**。 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editroleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editroleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoleQuest">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" width="30%" @close="resetDefKeys">
      <!-- 树形权限主体区域 -->
      <el-tree
        :data="rightTree"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRoleDialog: false,
      editRoleDialog: false,
      rightDialogVisible: false,
      rightTree: [],
      // 树形控件的所有属性绑定
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 当前角色所有三级权限id
      defKeys: [],
      // 将要分配权限的id数组
      allotId: [],
      // 将要分配权限的角色
      role: null,
      // 添加角色表单
      roleForm: {
        rolename: '',
        roleDescription: ''
      },
      // 修改角色表单
      editroleForm: {},
      // 添加角色验证规则
      roleFormRules: {
        rolename: [
          {
            required: true,
            message: '请填写角色名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 8,
            message: '角色名称长度在2~8个字符之间',
            trigger: 'blur'
          }
        ],
        roleDescription: [
          {
            required: true,
            message: '请填写角色描述',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 40,
            message: '角色描述长度在4~40个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 修改角色验证规则
      editRoleFormRules: {
        roleName: [
          {
            min: 2,
            max: 8,
            message: '角色名称长度在2~8个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            min: 4,
            max: 40,
            message: '角色描述长度在4~40个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 添加角色对话框
    addRole() {
      this.addRoleDialog = true
    },
    // 发送添加角色请求
    addRoleQuest() {
      // 预验证
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          // 如果校验通过，那么发起ajax请求
          const { data: res } = await this.$http.post('roles', {
            roleName: this.roleForm.rolename,
            roleDesc: this.roleForm.roleDescription
          })
          this.addRoleDialog = false
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          } else {
            this.getRolesList()
            return this.$message.success(res.meta.msg)
          }
        } else return undefined
      })
    },
    // 关闭添加角色对话框，重置表单数据
    resetRoleForm() {
      this.$refs.roleForm.resetFields()
    },
    // 修改角色对话框显示
    async editRole(id) {
      this.editRoleDialog = true
      // 根据角色id查询角色信息
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editroleForm = res.data
    },
    // 提交修改用户表单
    editRoleQuest() {
      // 预校验
      this.$refs.editroleForm.validate(async valid => {
        if (!valid) return undefined
        const { data: res } = await this.$http.put(
          `roles/${this.editroleForm.roleId}`,
          {
            roleName: this.editroleForm.roleName,
            roleDesc: this.editroleForm.roleDesc
          }
        )
        this.editRoleDialog = false
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getRolesList()
        this.$message.success('编辑成功')
      })
    },
    // 重置修改用户表单
    resetEditRoleForm() {
      this.$refs.editroleForm.resetFields()
    },
    // 删除角色
    remove(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除权限对话框
    removeRight(role, rightId) {
      this.$confirm('此操作将永久删除该权限', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          // 防止在删除权限的时候整个页面刷新
          role.children = res.data
          return this.$message.success(res.meta.msg)
        })
        .catch(() => {
          return this.$message.info('操作已取消')
        })
    },
    // 分配权限对话框的显示与隐藏
    async showSetRightDialog(role) {
      this.rightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) this.$message.error('获取权限失败')
      this.rightTree = res.data
      this.getLeafKey(role, this.defKeys)
      this.role = role
    },
    // 通过递归的形式，来获取当前角色的所有三级权限，并添加到 defKeys 数组中
    getLeafKey(node, arr) {
      // 如果该节点没有 children 属性，那么证明该节点为三级权限
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果有children 属性，那么通过递归来查找出三级权限
      node.children.forEach((item, index) => {
        this.getLeafKey(item, arr)
      })
    },
    // 关闭分配权限对话框时，重置三级权限列表
    resetDefKeys() {
      this.defKeys = []
    },
    // 提交角色分配权限
    async allotRight() {
      this.rightDialogVisible = false
      this.allotId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = this.allotId.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.role.id}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) this.$message.error('分配权限失败')
      this.getRolesList()
      this.$message.success('分配权限成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0;
}
.el-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
}
:last-child.el-row {
  border-bottom: none;
}
.borderTop {
  border-top: 1px solid #eee;
}
.borderBottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
</style>
